package com.ipan.weixin.security;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.ipan.weixin.WxConfiguration;
import com.ipan.weixin.util.WxMessageVerifyUtils;

/**
 * 微信签名验证
 * 
 * @author iPan
 * @version 2013-12-27
 */
public class WxVerifier implements Verifiable {

	@SuppressWarnings("rawtypes")
	public boolean verify(Map paramMap) {
		 String signature = getParamValue(paramMap, "signature"); // 微信加密签名
		 String timestamp = getParamValue(paramMap, "timestamp"); // 时间戳
		 String nonce = getParamValue(paramMap, "nonce"); // 随机数
		 String token = WxConfiguration.getInstance().getToken();
		 if (StringUtils.isEmpty(signature)) {
			 return false;
		 } else {
			 return WxMessageVerifyUtils.verify(signature, timestamp, nonce, token);
		 }
	}

	@SuppressWarnings("rawtypes")
	private String getParamValue(Map paramMap, String key) {
		Object values = paramMap.get(key);
		String result = null;
		if (values != null) {
			if (values instanceof String[] && ((String[])values).length > 0) {
				result = ((String[])values)[0];
			} else if (values instanceof String) {
				result = (String) values;
			}
		}
		return result;
	}
}
